package com.geek.framework.study.validate.advice;


import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import java.util.ArrayList;
import java.util.List;

@ControllerAdvice
public class GlobalExceptionHandleAdvice {


    @ExceptionHandler(value = BindException.class)
    public ResponseEntity bind(BindException e) {
        ResponseEntity.BodyBuilder ok = ResponseEntity.ok();

        List<ArgumentInvalidResult> invalidArguments = new ArrayList<>();
        //解析原错误信息，封装后返回，此处返回非法的字段名称，原始值，错误信息
        for (FieldError error : e.getBindingResult().getFieldErrors()) {
            ArgumentInvalidResult invalidArgument = new ArgumentInvalidResult();
            invalidArgument.setDefaultMessage(error.getDefaultMessage());
            invalidArgument.setField(error.getField());
            invalidArgument.setRejectedValue(error.getRejectedValue());
            invalidArguments.add(invalidArgument);
        }

        return ok.body(invalidArguments);
    }

    @ExceptionHandler(value = Exception.class)
    public ResponseEntity exception(Exception e) {
        ResponseEntity.BodyBuilder ok = ResponseEntity.ok();
        return ok.body(e.getLocalizedMessage());
    }


    public static class ArgumentInvalidResult {
        private String field;
        private Object rejectedValue;
        private String defaultMessage;

        public String getField() {
            return field;
        }

        public void setField(String field) {
            this.field = field;
        }

        public Object getRejectedValue() {
            return rejectedValue;
        }

        public void setRejectedValue(Object rejectedValue) {
            this.rejectedValue = rejectedValue;
        }

        public String getDefaultMessage() {
            return defaultMessage;
        }

        public void setDefaultMessage(String defaultMessage) {
            this.defaultMessage = defaultMessage;
        }
    }
}
